package com.youan.serve.service.impl;

import com.youan.pangu.base.bean.ElementTree;
import com.youan.serve.dao.domain.Function;
import com.youan.serve.service.ElementTreeService;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class ElementTreeServiceImpl implements ElementTreeService {
    @Override
    public <T> List<ElementTree> buildElementTree(List<T> treeList, Class<T> className) throws IllegalAccessException, InstantiationException {
        // 组成ElementTree 将父节点为空的组成ElementTree，他们作为根目录
        List<ElementTree> elementTreeList = new ArrayList<ElementTree>();
        // 循环构建ElementTree集合
        for(int i=0; i<treeList.size(); i++) {
            T elementTree=className.newInstance();
            elementTree = treeList.get(i);
            // 构建前台节点id和label
            // 如果父节点是空，证明是根节点，添加到ElementTreeList
//            if(StringUtils.isEmpty(elementTree.)) {
//                elementTreeList.add(ElementTree);
//                packingChildElementTreeList(ElementTree,treeList,ElementTree.getFunId());
//            }
        }
        // 将子节点转载入父节点
        return elementTreeList;
    }

    /**
     * 递归调用，设置child
     * @param ElementTree
     * @param functionList
     * @param parentid
     */
    private void packingChildElementTreeList(ElementTree ElementTree, List<Function> functionList, String parentid) {
        if(!isParentRoot(functionList,parentid)) {
            return;
        }
        List<ElementTree> ElementTreeList = new ArrayList<ElementTree>();
        for(int i=0; i<functionList.size(); i++) {
            Function subElementTree =  functionList.get(i);
            if((!StringUtils.isEmpty(subElementTree.getParentId()))&&subElementTree.getParentId().equals(parentid)) {
                ElementTreeList.add(subElementTree);
                packingChildElementTreeList(subElementTree,functionList,subElementTree.getFunId());
            }
        }
        ElementTree.setChildren(ElementTreeList);
    }

    /**
     * 判断该节点是否是父节点
     * @return
     */
    private Boolean isParentRoot(List<Function> routerList,String parentId) {
        for(int i=0; i<routerList.size(); i++) {
            if((!StringUtils.isEmpty(routerList.get(i).getParentId()))&&routerList.get(i).getParentId().equals(parentId)) {
                return true;
            }
        }
        return false;
    }

}
